// 定义regionTree仓库
import { defineStore } from 'pinia';
import { reqRegionTree } from '@/api/home/systemManagement';
import { reqDeviceAll, reqProductAll } from '@/api/home/fileManagement';
import useUserStore from '@/store/modules/user';

const constantStore = defineStore('Constant', () => {
  // 地域树
  const regionTreeData: any = ref([]);
  // 地域树loading状态
  const loading = ref(false);
  const { tenantInfo } = useUserStore();
  // 获取地域树的函数
  const getRegionTree = async () => {
    loading.value = true;
    try {
      const { data } = await reqRegionTree({ regionId: tenantInfo?.regionId || '' });
      regionTreeData.value = [data];
      // 手动添加未分组选项
      regionTreeData.value.push({
        name: '未分组',
        weight: -1,
      });
    } catch (error) {}
    loading.value = false;
  };

  // 设备类型
  const deviceTypeOption: any = ref([]);
  const deviceTypeMap = ref({});
  // 产品类型
  const productTypeOption: any = ref([]);
  const productTypeMap = ref({});

  // 获取设备类型的函数
  const getDeviceType = async () => {
    if (deviceTypeOption.value.length > 0) {
      return;
    }
    const deviceRes = await reqDeviceAll();
    // 设备类型
    deviceTypeOption.value = deviceRes.map((item) => ({
      value: item.categoryKey,
      label: item.name,
    }));
    //设备映射
    const tempDeviceMap = {};
    deviceRes.forEach((item) => {
      tempDeviceMap[item.categoryKey] = item.name;
    });
    deviceTypeMap.value = tempDeviceMap;
  };

  // 获取产品类型的函数
  const getProductType = async () => {
    if (productTypeOption.value.length > 0) {
      return;
    }
    const productRes = await reqProductAll();
    // 产品类型
    productTypeOption.value = productRes.map((item) => ({
      value: item.id.toString(),
      label: item.name,
      productKey: item.productKey,
    }));
    //产品映射
    const tempProductMap = {};
    productRes.forEach((item) => {
      tempProductMap[item.id] = item.name;
    });
    productTypeMap.value = tempProductMap;
  };

  // 获得设备和产品类型
  const getDeviceAndProductType = () => {
    getDeviceType();
    getProductType();
  };

  return {
    regionTreeData,
    loading,
    getRegionTree,
    getDeviceAndProductType,
    productTypeOption,
    productTypeMap,
    deviceTypeOption,
    deviceTypeMap,
  };
});

export default constantStore;
